package com.congee02.rewrite;

import com.congee02.TreeNode;

import java.util.ArrayList;
import java.util.List;

class Solution {

    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        morrisIn(root, ans);
        return ans;
    }

    // 中后
    private void morrisIn(TreeNode root, List<Integer> ans) {

        TreeNode cur = root;

        while (cur != null) {
            TreeNode mostRight = cur.left;
            if (mostRight != null) {

                while (mostRight.right != null && mostRight.right != cur) {
                    mostRight = mostRight.right;
                }

                if (mostRight.right == null) {
                    mostRight.right = cur;
                    cur = cur.left;
                } else {
                    ans.add(cur.val);
                    mostRight.right = null;
                    cur = cur.right;
                }
            } else {
                ans.add(cur.val);
                cur = cur.right;
            }
        }

    }
}